'use strict';
const {
  Service,
} = require('egg');
const { get } = require("lodash");

class CheckInRecordService extends Service {


  async findByWorkCardId(id) {
    const {
      app,
    } = this;

    const ret = await app.mysql.select('t_node_record', {
      where: {
        workcardId: id,
      },
      columns: [
        'id',
        'workcardId',
        'state',
        'content',
        'remark',
        'create_time',
        'update_time',
      ],
      limit: 1,
      offset: 0,
    });

    if (!ret || !ret.length) {
      return {};
    }
    return ret[0];
  }

  /**
   * 更新添加操作
   * @param {String}} workcardId
   * @param {int} state
   * @param {String} content
   * @param {int} type 0:插入，1：更新。
   */
  async dealByWorkCardId(workcardId, state, content,type = 1) {
    workcardId = workcardId.trim();
    const {
      ctx,app
    } = this;

    const dealData = {
      workcardId,
      state,
    };
	   app.logger.info("服务信息：%s", type);
    const dealTime = this.app.format_time();
    if (!this.app.lodash.isEmpty(content) && type === 0) { // 插入
      Object.assign(dealData, { content: JSON.stringify(content) })
    }
    if(!this.app.lodash.isEmpty(content) && type === 1) { // 更新
      let tempcontent = this.app.lodash.get(content,"content",false);
      if(tempcontent !== false) {
        Object.assign(dealData,  { content: JSON.stringify(tempcontent)}); //附加更新字段
        delete content.content;
      }
      Object.assign(dealData,content);
    }
    if(!this.app.lodash.isEmpty(content) && type === 3) { // 特殊处理
      let specialData = {};
      Object.assign(specialData,content);
      Object.assign(specialData, { update_time: dealTime,workcardId });
	  	   app.logger.info("服务信息：%s", JSON.stringify(specialData));
      await this.app.mysql.update('t_node_record', specialData, {
        where: {
          workcardId,
        },
      });
      return;
	   app.logger.info("服务信息：%s", 0);
    }
    const ret = await this.findByWorkCardId(workcardId);



    if (this.app.lodash.isEmpty(ret) && type === 0) { // 插入操作 (没有信息)
      // 没有基本信息进行插入操作
      Object.assign(dealData, { create_time: dealTime,mobile: content.buyer_mobile });
      await this.app.mysql.insert('t_node_record', dealData);
    } else if(!this.app.lodash.isEmpty(ret) && type === 1) { // 更新
      Object.assign(dealData, { update_time: dealTime });
      await this.app.mysql.update('t_node_record', dealData, {
        where: {
          workcardId,
        },
      });
    }
  }

  /**
   * 批量处理拉去订单
   * @param {Array} lists
   */
  async totalDealData(lists) {


    if (!this.app.lodash.isEmpty(lists)) { // 插入操作 (没有信息)
      // 没有基本信息进行插入操作
      const insertData = [];
      const { ctx } = this;
      // let func = this.findByWorkCardId;
      // let that = this;
      // this.app.lodash.forEach(lists, item => {

      // });


      for (let i =0;i< lists.service_task_d_o.length;i++) {
        let item = lists.service_task_d_o[i];

        const ret = await this.findByWorkCardId(item.service_order_id);
        if (this.app.lodash.isEmpty(ret)) {
          insertData.push({
            workcardId: item.service_order_id,
            state: 0, //待接单
            content: JSON.stringify(item),
            create_time: this.app.format_time()
          });
        }
      }

      if (!this.app.lodash.isEmpty(insertData)) { // 存在插入操作
        this.app.mysql.insert('t_node_record', insertData);
      }
    }
  }

  async getTotal(param = {}) {
    const { ctx, app } = this;

    const ret = await app.mysql.select('t_node_record', {
      where: param,
      columns: [
        'id',
        'workcardId',
        'state',
        'content',
        'create_time',
        'update_time',
      ]
    });

    if (this.app.lodash.isEmpty(ret)) {
      return 0;
    }
    return ret.length;
  }

  /**
   *
   * @param {int} page
   * @param {int} pageSize
   * @param {int} param
   */
  async getPagination(page = 1, pageSize = 10, param = {}) {
    const { ctx, app } = this;

    let offset = (page - 1) * pageSize;
    const ret = await app.mysql.select('t_node_record', {
      where: param,
      columns: [
        'id',
        'workcardId',
        'state',
        'mobile',
        'remark',
        'fetch_express_num',
        'fetch_express_name',
        'send_express_num',
        'send_express_name',
        'content',
        'create_time',
        'update_time',
      ],
      orders: [['id','desc']], // 排序方式
      limit: pageSize,
      offset,
    });

    let total = await this.getTotal(param);

    if (!this.app.lodash.isEmpty(ret)) {
      this.app.lodash.forEach(ret, function (item, key) {
        ret[key].content = JSON.parse(item.content);
      });
    }
    let res = {
      data: this.app.lodash.isEmpty(ret) ? [] : ret,
      total,
      page,
      pageSize
    };
    return res;
  }

  async getScope(start,end,session) {
    const { app } = this;
    const apiInfo = app.config.api.tjava;
    const result = await app.curl(apiInfo + "/tjava/scope", {
      method: 'POST',
      dataType: 'json',
      timeout: 3000,
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
       start,
       end,
       session
      },
    });
    this.app.logger.info(JSON.stringify(result.data));

    if(get(result.data,"tmall_servicecenter_tasks_search_response","") === "") {
      let resError = get(result.data,"error_response","");
      if(resError !== "") {
        if( resError.code === 27 && resError.msg === "Invalid session") {
          this.ctx.throw(401, '登陆过期, 请重新登陆'); //是否为回话失败
          return;
        }
      }
      this.ctx.throw(500, '服务异常'); // 如果失败，直接抛出异常
      return;
    }
   return result.data.tmall_servicecenter_tasks_search_response;
  }
  
  

  async getDetail(id,session) {
    const { app } = this;
    const apiInfo = app.config.api.tjava;
    const result = await app.curl(apiInfo+ "/tjava/detail", {
      method: 'POST',
      dataType: 'json',
      timeout: 3000,
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
       session
      },
    });
    this.app.logger.info(JSON.stringify(result.data));
    if(get(result.data,"tmall_servicecenter_task_get_response","") === "") {
      let resError = get(result.data,"error_response","");
      if(resError !== "") {
        if( resError.code === 27 && resError.msg === "Invalid session") {
          this.ctx.throw(401, '登陆过期, 请重新登陆'); //是否为回话失败
          return;
        }
      }
      this.ctx.throw(500, '服务异常'); // 如果失败，直接抛出异常
      return;
    }
   return result.data.tmall_servicecenter_task_get_response;
  }

}

module.exports = CheckInRecordService;
